package cn.rkylin.oms.item.adapter;

import cn.rkylin.apollo.common.util.HttpUtils;
import cn.rkylin.core.IDataBaseFactory;
import cn.rkylin.core.utils.StringUtil;
import cn.rkylin.oms.common.dto.DBLog;
import cn.rkylin.oms.common.utils.DateUtil;
import cn.rkylin.oms.common.utils.LogUtil;
import cn.rkylin.oms.item.dao.IItemDAO;
import cn.rkylin.oms.item.domain.Item;
import cn.rkylin.oms.item.request.PushItemDeListing;
import cn.rkylin.oms.item.request.PushItemListing;
import cn.rkylin.oms.item.request.PushItemQuantityUpdate;
import cn.rkylin.oms.item.vo.ItemVO;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2018-1-18.
 */
@Service("vipItemVisitor")
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class VipItemVisitor extends ItemVisitor {

    private static final Log logger = LogFactory.getLog(TaoBaoItemVisitor.class);
    private static final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Autowired
    private IDataBaseFactory dao;
    @Autowired
    private IItemDAO itemDAO;
    @Autowired
    LogUtil logUtil;

    /**
     * OMS调用地址
     */
    @Value("${oms.address}")
    private String omsUrl;

    /**
     * 构造函数
     */
    public VipItemVisitor() {

    }

    @Override
    public List<Item> getItemListByItemCode(String shopId, Map<String, Object> paramMap) throws Exception {
        return null;
    }

    @Override
    public List<Item> getItemListByModifyTime(String shopId, Map<String, Object> paramMap) throws Exception {
        return null;
    }

    @Override
    public List<Item> getItemListAll(String shopId) throws Exception {
        return null;
    }

    /**
     * 手动同步库存根据商品
     *
     * @param ecItemId
     * @return 错误消息
     * @throws Exception
     *             异常
     */
    @Override
    public String manualSynchStockByItem(String ecItemId) throws Exception {
        String allErrMsg = "";
        ItemVO searchItemVO = new ItemVO();
        searchItemVO.setEcItemId(ecItemId);
        List<ItemVO> itemDataList = itemDAO.selectDataForSynchStock(searchItemVO);

        if (itemDataList.size() > 0) {
            // 平台商品列表
            for (ItemVO itemData : itemDataList) {
                String errMsg = "";
                long sumStorage = 0; // 库存数合计
                ItemVO searchItemSkuVO = new ItemVO();
                searchItemSkuVO.setShopId(itemData.getShopId());
                searchItemSkuVO.setEcItemId(itemData.getEcItemId());
                List<ItemVO> itemSkuList = itemDAO.selectSkuForSynchStock(searchItemSkuVO);

                // 平台商品SKU列表
                for (ItemVO itemSku : itemSkuList) {
                    Map<String, Object> resultMap = this.synchStock(itemSku);
                    String msg = (String) resultMap.get("msg");
                    if ("该店铺未配置可推送仓库".equals(msg) || "该店铺未设置仓库推送比例".equals(msg)) {
                        return msg;
                    }
                    errMsg = errMsg + resultMap.get("msg");
                    sumStorage = sumStorage + Long.parseLong(resultMap.get("storage").toString());
                }

//                if ("".equals(errMsg)) {
//                    // 平台商品上下架
//                    if (sumStorage <= 0) { // 下架
//                        errMsg = errMsg + listDelist(itemData, false, sumStorage);
//                    }
//                }

                allErrMsg = allErrMsg + errMsg;
            }
        } else {
            ItemVO parameter = new ItemVO();
            parameter.setEcItemId(ecItemId);
            Item itemModel = (Item) dao.find("selectItemInfo", parameter);
            allErrMsg = "平台商品编码:" + itemModel.getEcItemCode() + "没有满足同步库存条件(店铺是否允许库存同步,平台商品是否允许库存同步,平台商品是否关联系统商品)\\n";
        }

        return allErrMsg;
    }

    @Override
    public String manualSynchStockBySku(String ecSkuId) throws Exception {
        // 按平台商品SKU同步库存
        String errMsg = "";
        ItemVO searchItemVO = new ItemVO();
        searchItemVO.setEcSkuId(ecSkuId);
        List<ItemVO> itemSkuList = itemDAO.selectSkuForSynchStock(searchItemVO);

        if (itemSkuList.size() > 0) {
            // 平台商品SKU列表
            for (ItemVO itemSku : itemSkuList) {
                Map<String, Object> resultMap = this.synchStock(itemSku);
                String msg = (String) resultMap.get("msg");
                if ("该店铺未配置可推送仓库".equals(msg) || "该店铺未设置仓库推送比例".equals(msg)) {
                    return msg;
                }
                errMsg = errMsg + resultMap.get("msg");
            }
        } else {
            errMsg = "没有满足同步库存条件(店铺是否允许库存同步,平台商品是否允许库存同步,平台商品是否关联系统商品)";
        }

        return errMsg;
    }

    /**
     * 自动同步店铺库存并上下架
     *
     * @param shopId
     * @return 错误消息
     * @throws Exception
     *             异常
     */
    @Override
    public String autoSynchStock(String shopId) throws Exception {
        String allErrMsg = "";
        ItemVO searchItemVO = new ItemVO();
        searchItemVO.setShopId(shopId);
        List<ItemVO> itemDataList = itemDAO.selectDataForSynchStock(searchItemVO);

        if (itemDataList.size() > 0) {
            // 平台商品列表
            for (ItemVO itemData : itemDataList) {
                String errMsg = "";
                long sumStorage = 0; // 库存数合计
                ItemVO searchItemSkuVO = new ItemVO();
                searchItemSkuVO.setShopId(shopId);
                searchItemSkuVO.setEcItemId(itemData.getEcItemId());
                List<ItemVO> itemSkuList = itemDAO.selectSkuForSynchStock(searchItemSkuVO);
                String autoList = itemData.getAutoList();

                // 平台商品SKU列表
                for (ItemVO itemSku : itemSkuList) {
                    Map<String, Object> resultMap = this.synchStock(itemSku);
                    String msg = (String) resultMap.get("msg");
                    if ("该店铺未配置可推送仓库".equals(msg) || "该店铺未设置仓库推送比例".equals(msg)) {
                        return msg;
                    }
                    errMsg = errMsg + resultMap.get("msg");
                    sumStorage = sumStorage + Long.parseLong(resultMap.get("storage").toString());
                }

                allErrMsg = allErrMsg + errMsg;
            }
        } else {
            allErrMsg = "没有满足同步库存条件(店铺是否允许库存同步,平台商品是否允许库存同步,平台商品是否关联系统商品)";
        }

        return allErrMsg;
    }

    /**
     * 同步店铺库存并上下架
     *
     * @param itemSku
     * @return 错误消息
     * @throws Exception
     *             异常
     */
    @SuppressWarnings("unchecked")
    private Map<String, Object> synchStock(ItemVO itemSku) throws Exception {
        Map<String, Object> returnMap = new HashMap<String, Object>();
        String returnMsg = "";
        long storage = 0; // 库存数

        // 计算系统商品库存数
        if ("n".equals(itemSku.getIsGroup())) { // 非组合商品
            JSONObject jsonObject = caculateStock(itemSku);
            if ("success".equals(jsonObject.get("result"))) {
                storage = Integer.parseInt(jsonObject.get("storage").toString());
            } else {
                String msg = (String) jsonObject.get("msg");
                logUtil.info(new DBLog(itemSku.getEcSkuCode(), "", "synchStock",
                        DateUtil.getCurrentDateStr() + " 平台规格编码为【" + itemSku.getEcSkuCode() + "】同步失败," + msg));
                if ("该店铺未配置可推送仓库".equals(msg) || "该店铺未设置仓库推送比例".equals(msg)) {
                    returnMap.put("msg", msg);
                    returnMap.put("storage", 0);
                    return returnMap;
                }
                returnMsg = returnMsg + "平台规格编码:" + itemSku.getEcSkuCode() + msg + "\\n";
            }
        } else { // 组合商品
            ItemVO searchItemVO = new ItemVO();
            searchItemVO.setEcSkuId(itemSku.getEcSkuId());
            List<ItemVO> groupSkuList = itemDAO.selectSkuForGroup(searchItemVO);

            for (int i = 0; i < groupSkuList.size(); i++) {
                ItemVO groupSku = groupSkuList.get(i);
                groupSku.setPrjId(itemSku.getPrjId());
                groupSku.setShopId(itemSku.getShopId());
                JSONObject jsonObject = caculateStock(groupSku);
                if ("success".equals(jsonObject.get("result"))) {
                    long tempStorage = Integer.parseInt(jsonObject.get("storage").toString());
                    double upRate = Float.parseFloat(groupSku.getUpRate());
                    long num = Integer.parseInt(groupSku.getNum());
                    // 库存 = 库存数 * 推送系数 / 数量 向下取整
                    tempStorage = (long) Math.floor(tempStorage * upRate / num);

                    // 取最小值
                    if (i == 0) {
                        storage = tempStorage;
                    } else {
                        if (tempStorage < storage) {
                            storage = tempStorage;
                        }
                    }
                } else {
                    String msg = (String) jsonObject.get("msg");
                    logUtil.info(new DBLog(itemSku.getEcSkuCode(), "", "synchStock",
                            DateUtil.getCurrentDateStr() + " 平台规格编码为【" + itemSku.getEcSkuCode() + "】同步失败," + msg));
                    if ("该店铺未配置可推送仓库".equals(msg) || "该店铺未设置仓库推送比例".equals(msg)) {
                        returnMap.put("msg", msg);
                        returnMap.put("storage", 0);
                        return returnMap;
                    }
                    returnMsg = returnMsg + "平台规格编码:" + itemSku.getEcSkuCode() + msg + "\\n";
                    break;
                }
            }
        }

        if ("".equals(returnMsg)) {
            // 库存同步
            PushItemQuantityUpdate pushItemQuantityUpdate = new PushItemQuantityUpdate();
            pushItemQuantityUpdate.setShopId(itemSku.getShopId());
            pushItemQuantityUpdate.setEcItemCode(itemSku.getEcItemCode());
            String ecSkuCode = itemSku.getEcSkuCode();
            if (ecSkuCode != null && "0".equals(ecSkuCode)) {
                ecSkuCode = null;
            }
            pushItemQuantityUpdate.setSkuId(ecSkuCode);
            pushItemQuantityUpdate.setNum(String.valueOf(storage));
            String requestParams = JSON.toJSONString(pushItemQuantityUpdate);
            String resJson = HttpUtils.sendByPostJson(omsUrl + "pushItem/pushItemQuantityUpdate.action", requestParams);
            Map<String, Object> resultMap = JSON.parseObject(resJson, Map.class);
            if ("n".equals(resultMap.get("success"))) {
                logUtil.info(new DBLog(itemSku.getEcSkuCode(), "", "synchStock",
                        DateUtil.getCurrentDateStr() + " 自动同步库存平台规格编码为【" + itemSku.getEcSkuCode() + "】同步失败," + resultMap.get("msg")));
                returnMsg = returnMsg + "平台规格编码:" + itemSku.getEcSkuCode() + resultMap.get("msg") + "\\n";
                // TODO 发邮件
            }
        }

        returnMap.put("msg", returnMsg);
        returnMap.put("storage", storage);
        return returnMap;
    }

    /**
     * 计算库存数
     *
     * @param itemVO
     *            平台商品VO
     * @return 计算结果
     * @throws Exception
     *             异常
     */
    private JSONObject caculateStock(ItemVO itemVO) throws Exception {
        String requestStr = StringUtil.format("stockPush/caculateStock.action?projectId=%s&shopIds=%s&skuIds=%s", itemVO.getPrjId(),
                itemVO.getShopId(), itemVO.getSkuId());
        String requestUrl = omsUrl + requestStr;
        String resJson = HttpUtils.sendByGet(requestUrl, null);
        JSONObject jsonObject = JSON.parseObject(resJson, JSONObject.class);

        return jsonObject;
    }
}
